package org.example;

import java.util.ArrayList;
import java.util.List;

/**
 * 异步事务工具
 * 多线程同时运行 如果有一个错误就全部回滚
 * */
public class AsynchronousTransactionUtils {

    //用于存放需要执行的进程列表
    private List<Runnable> runnableList = new ArrayList<>();

    private int trueNumber = 0;
    private int falseNumber = 0;
    private int maxNumber = 0;


    public void add(Runnable runnable){
        this.runnableList.add(runnable);
        this.maxNumber++;
    }

    public boolean run(){
        for (Runnable runnable :this.runnableList){
            try {
                runnable.run();
                this.trueNumber ++;
            }catch (Exception e){
                this.falseNumber++;
            }

        }
        return isSucceed();
    }

    //判断运行结束
    public boolean sleep(long time,long flagTime){
        //超时时间大于十秒直接false
        if (time>flagTime){
            return false;
        }
        return this.trueNumber+falseNumber == maxNumber;
    }
    //判断是否有错误
    public boolean isSucceed(){
        return this.falseNumber ==0;
    }


}
